/*****  Component, by Ben Bi <prince.bi@gmail.com>  created at: 12/23/2009 4:10:45 PM  *****/

/********   Notes:  *******
 *  Two tags need to be replaced with the module name, they are:
 *  cottonOrder
 *  CottonOrder
 */



/***** variables declartion section, begin *****/
var cottonOrderInputMode = wacFormInputMode.add;
var cottonOrderObj = {};
var cottonOrderAuditAction = {};  // process audit action

/***** variables declartion section, end *****/

/***** init section, begin *****/
$(document).ready(
    function() {
        cottonOrderAuditAction = new CottonOrderAuditAction();

        initCottonOrderFormDialog();

        initCottonOrderForm();

        bindCottonOrderEvents();
    }
);

function bindCottonOrderEvents()
{
    $("#cottonOrderFormDialog").bind('dialogopen', function(event, ui)
    {
        initCottonOrderFormData();
//        wacDebugLog("calling " + moduleName + ":" + wacModelObj.cottonOrder.name);//
    });

    $("#cottonOrderFormDialog").bind('dialogclose', function(event, ui)
    {
        $.validationEngine.closePrompt(".formError", true);
    });

    $("#cottonOrder_btnSubmit").bind('click', function (e)
    {
        submitCottonOrderForm();
    });

    $("#cottonOrder_btnClose").bind('click', function (e)
    {
        $("#cottonOrderFormDialog").dialog('close');
    });

    // fix dialog div didnt remove bug, remove it by this way
    $('#appStorehouseRightPane').bind('tabsremove', function(event, ui) {
//        wacDebugLog($(event.target).attr("id"));
//        wacDebugLog(ui.panel.id);
        if(ui.panel.id == "t1012")
        {
            $("div[aria-labelledby='ui-dialog-title-cottonOrderFormDialog']").remove();
            $("#cottonOrderFormDialog").remove();
        }        
    });
}


function initCottonOrderFormDialog()
{
//    wacDebugLog("initCottonOrderFormDialog.");
    $("#cottonOrderFormDialog").dialog({
            bgiframe: true,
            modal: true,
            width: 850,
            height: 550,
            autoOpen: false,
            buttons: {},
            zIndex: 100
        });
}

function initCottonOrderForm()
{
    $("#cottonOrderForm").validationEngine();

    $.datepicker.setDefaults($.datepicker.regional['zh-CN']);
    $("#cottonOrder_start_date, #cottonOrder_delivery_date").datepicker();
//    $("#start_date, #delivery_date").datepicker({
//        duration: '',
//        showTime: true,
//        constrainInput: false,
//        stepMinutes: 1,
//        stepHours: 1,
//        altTimeField: '',
//        time24h: false
//     });

    $('.wacFormContent .left, .wacFormContent input, .wacFormContent textarea, .wacFormContent select').focus(function(){
        $(this).parents('.wacFormContent').addClass("wacFormOver");
    }).blur(function(){
        $(this).parents('.wacFormContent').removeClass("wacFormOver");
    });

    $('.wacFormContentA .left, .wacFormContentA input, .wacFormContentA textarea, .wacFormContentA select').focus(function(){
        $(this).parents('.wacFormRow').addClass("wacFormOver");
    }).blur(function(){
        $(this).parents('.wacFormRow').removeClass("wacFormOver");
    });


}

function initCottonOrderFormData()
{
    wacShowBlockUILoading("#cottonOrderFormDialog");
    $('#cottonOrder_supplier_id, #cottonOrder_factory_id, #cottonOrder_production_order_id, #cottonOrder_goods_amount_unit_code').empty();

    var params = {
        "data_format" :'json'
    };

    $.ajax({
        url: BASE_URL + "cottonOrder/getFormData",
        global: true,
        type: "GET",
        data: params,
        dataType: "json",
        success: function(jsonData){
            initCottonOrderFormDataCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function initCottonOrderFormDataCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       alert(jsonData.info.error_info);
   }
   else
    {
        var selectedIndex = 0;

        for(i=0;i<jsonData['items']['unit'].length;i++)
        {
            $('<option value="' + jsonData['items']['unit'][i].key +'">' + jsonData['items']['unit'][i].value +'</option>').appendTo("#cottonOrder_goods_amount_unit_code");
        }

        for(i=0;i<jsonData['items']['supplier'].length;i++)
        {
            $('<option value="' + jsonData['items']['supplier'][i].key +'">' + jsonData['items']['supplier'][i].value +'</option>').appendTo("#cottonOrder_supplier_id");
        }
   }

   setupCottonOrderFormDefaultValues(jsonData['items']['default']);

   wacHideBlockUI("#cottonOrderFormDialog");

//   wacDebugLog($.dump(jsonData));
}

function setupCottonOrderFormDefaultValues(defaultValueObj)
{
    if(cottonOrderInputMode == wacFormInputMode.add)   // use default values
    {
        $("#cottonOrder_id").attr("value", 0);
        $('#cottonOrder_production_order_id').flexbox(BASE_URL + 'productionOrder/GetIdCodeHashInFormat/status/audited?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "production_order_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });

        $('#cottonOrder_factory_id').flexbox(BASE_URL + 'factory/GetDyeWeaveFactoryIdNameHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "factory_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });

        $("#cottonOrder_goods_amount_unit_code option:[value='"+ defaultValueObj.cotton_unit_code +"']").attr('selected', 'selected');
//        $("#cottonOrder_factory_id option:[value='"+ defaultValueObj.factory_id +"']").attr('selected', 'selected');
//        $("#cottonOrder_supplier_id option:[value='"+ defaultValueObj.suplier_id +"']").attr('selected', 'selected');
    }
    else  // use edit obj values
    {
        $('#cottonOrder_production_order_id').flexbox(BASE_URL + 'productionOrder/GetIdCodeHashInFormat/status/audited?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            initialValue: cottonOrderObj.production_order_id,
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "production_order_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });
        $('#cottonOrder_production_order_id_input').val(cottonOrderObj.production_order_code);

        $('#cottonOrder_factory_id').flexbox(BASE_URL + 'factory/GetDyeWeaveFactoryIdNameHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            initialValue: cottonOrderObj.factory_id,
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "factory_id",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });
        $('#cottonOrder_factory_id_input').val(cottonOrderObj.factory_name);

        $("#cottonOrder_start_date").attr("value", cottonOrderObj.start_date);
        $("#cottonOrder_delivery_date").attr("value", cottonOrderObj.delivery_date);
        $("#cottonOrder_code").attr("value", cottonOrderObj.code);
//        $("#cottonOrder_batch").attr("value", cottonOrderObj.batch);
//        $("#cottonOrder_goods_amount").attr("value", cottonOrderObj.goods_amount);
        $("#cottonOrder_id").attr("value", cottonOrderObj.id);
        $("#cottonOrderObj_memo").attr("value", cottonOrderObj.memo);

        $("#cottonOrder_goods_amount_unit_code option:[value='"+ cottonOrderObj.goods_amount_unit_code +"']").attr('selected', 'selected');
        $("#cottonOrder_supplier_id option:[value='"+ cottonOrderObj.supplier_id +"']").attr('selected', 'selected');
    }

//    wacDebugLog($.dump(cottonOrderObj));
//    wacDebugLog($.dump(defaultValueObj));
//    wacDebugLog("cottonOrderInputMode: " + cottonOrderInputMode);

}
/***** init section, end *****/


/**************  interaction section, begin  ***************/

// audit class
function CottonOrderAuditAction(){ 
    this.run = function(orderId){
        cottonOrderAudit(orderId);
    }
}

function cottonOrderAudit(orderId)
{
    wacShowBlockUILoading();
    var params = {
        "data_format" : 'json',
        "cotton_order_id" : orderId
    };
//    cottonOrderObj = $("#cottonOrderList").getRowData(orderId);
//    console.log($.dump(cottonOrderObj));

    $.ajax({
        url: BASE_URL + "cottonOrder/audit",
        global: true,
        type: "GET",
        data: params,
        dataType: "json",
        success: function(jsonData){
            cottonOrderAuditCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function cottonOrderAuditCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       wacShowTips(jsonData.info.error_info);
   }
   else
   {
       wacShowTips(jsonData.info.tips);
       $("#cottonOrderList").trigger("reloadGrid");
   }
   wacHideBlockUI();
//   wacDebugLog($.dump(jsonData));
}

function cottonOrderOpenModuleForm(moduleFormName, moduleName, inputMode, rowid)
{
    cottonOrderInputMode = inputMode;

    if(rowid === undefined){
        cottonOrderObj = {};
    }
    else
    {
        cottonOrderObj = $("#" + moduleName +"List").getRowData(rowid);
    }

    $('#'+moduleFormName).dialog('open');
}

function validateCottonOrderForm()
{
    var validateFlag = true;

    if (!$("#cottonOrderForm").validationEngine({returnIsValid:true}))
    {
        validateFlag = false;
        return validateFlag;
    }

    var startDate    = $("#cottonOrder_start_date").datepicker( 'getDate' );
    var deliveryDate = $("#cottonOrder_delivery_date").datepicker( 'getDate' );
    if(deliveryDate <= startDate)
    {
        wacShowTips("发货日期不得早于开始日期!");
        validateFlag = false;
    }

    return validateFlag;
}

function submitCottonOrderForm()
{
    if(!validateCottonOrderForm()){
        return;
    }

    wacShowBlockUILoading("#cottonOrderFormDialog", "处理中...");

    var extraParams = "data_format=json";
    var submitUrl;

    if(cottonOrderInputMode == wacFormInputMode.add){
        submitUrl = BASE_URL + "cottonOrder/add";
    }
    else{
        submitUrl = BASE_URL + "cottonOrder/edit";
    }


    $.ajax({
        url: submitUrl,
//        url: BASE_URL + "test/ajaxTest" ,
        global: true,
        type: "GET",
        data: $("#cottonOrderForm").serialize() + "&" + extraParams,
        dataType: "json",
        success: function(jsonData){
            submitCottonOrderFormCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function submitCottonOrderFormCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       wacShowTips(jsonData.info.error_info);
   }
   else
   {
       wacShowTips(jsonData.info.tips);
       $("#cottonOrderList").trigger("reloadGrid");
   }

   wacHideBlockUI("#cottonOrderFormDialog");

//   wacDebugLog($.dump(jsonData));
}

/**************  interaction section, end  ***************/